<?php
namespace app\api\controller;

use think\Db;



header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Max-Age:3600");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,Token,ID");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS');


class User extends Check
{
    protected function _initialize(){
        parent::_initialize();
    }
    public function index()
    {
        //轮播图
        $slide=Db::name('slide')->where('cid',1)->where('status',1)->order('sort desc')->field('image')->select();
        if(!empty($slide)){
            foreach ($slide as $k=>$v) {
                $slide[$k]['image'] = 'http://' . $_SERVER['SERVER_NAME'].'/public'.$v['image'];
            }
        }

        //公告单条
        $notice = Db::name('notice')->where('del_time', null)->order('id desc')->field('del_time,content', true)->find();

        //商品列表
        $good=Db::name('good')->where('del_time',null)->order('id desc')->field('id,name,price,image,brief')->select();
        foreach ($good as $k=>$v) {
            $good[$k]['image'] = 'http://' . $_SERVER['SERVER_NAME'].'/public'.$v['image'];
        }

        //组装数据
        $send = [
            'slide' => $slide,
            'notice' => $notice,
            'good' => $good
        ];
        return $this->splash(1,'获取成功',$send);
    }
//  	/**
//     * 修改密码
//     */
//    public function edit_password()
//    {
//		$data=request()->post();
//      	if(!$data['id']||!$data['old_password']||!$data['new_password']){
//          return $this->splash(0,'信息不完整，请重试');
//        }
//      	$info=Db::table('os_user')->where(['id'=>$data['id']])->find();
//      	if($info['password']!=md5($data['old_password'])){
//          return $this->splash(0,'原始密码错误，请重试');
//        }
//      	$r=Db::table('os_user')->where(['id'=>$data['id']])->update(['password'=>md5($data['new_password'])]);
//      	if($r){
//          return $this->splash(1,'密码更改成功');
//        }else{
//          return $this->splash(0,'密码更改失败，请稍候重试');
//        }
//    }
//  	/**
//     * 获取个人信息
//     */
//    public function get_info()
//    {
//		$data=request()->post();
//      	if(!$data['id']){
//          return $this->splash(0,'信息不完整，请重试');
//        }
//      	$info=Db::table('os_user')->where(['id'=>$data['id']])->field('id,username,sex,age,image')->find();
//      	if($info){
//          $send=[
//            'user'=>$info,
//            'url'=>'http://'.$_SERVER['SERVER_NAME'].'/public/',
//          ];
//          return $this->splash(1,'获取成功',$send);
//        }else{
//          return $this->splash(0,'获取失败，请稍候重试');
//        }
//    }
//  	/**
//     * 更改个人信息
//     */
//    public function edit_info()
//    {
//		$data=request()->post();
//      	if(!$data['username']||!$data['sex']||!$data['age']||!$data['image']||!$data['id']){
//          return $this->splash(0,'信息不完整，请重试');
//        }
//      	$save=[
//          'username'=>$data['username'],
//          'age'=>$data['age'],
//          'sex'=>$data['sex'],
//          'image'=>$data['image'],
//        ];
//      	$r=Db::table('os_user')->where(['id'=>$data['id']])->update($save);
//      	if($r){
//          return $this->splash(1,'修改成功');
//        }else{
//          return $this->splash(0,'修改失败，请稍候重试');
//        }
//    }
//    /*
//     * 问题反馈
//     *  uid 用户id
//     *  content 内容
//     *  images 图片组
//     * */
//    public function feedback()
//    {
//		$data=request()->post();
//      	if(!$data['uid']||!$data['content']){
//          return $this->splash(0,'信息不完整，请重试');
//        }
//      	if($data['images']) {
//            if (is_array($data['images'])) {
//                $images = implode(',', $data['images']);
//            }else{
//                $images=$data['images'];
//            }
//        }else{
//      	    $images='';
//        }
//      	$save=[
//          'user_id'=>$data['uid'],
//          'content'=>$data['content'],
//          'images'=>$images,
//          'add_time'=>date('Y-m-d H:i:s',time()),
//        ];
//      	$r=Db::table('os_feedback')->insertGetId($save);
//      	if($r){
//          return $this->splash(1,'提交成功');
//        }else{
//          return $this->splash(0,'提交失败，请稍候重试');
//        }
//    }
    /**
     * 收货地址列表
     */
    public function address_list()
    {
        if($this->request->isPost()) {
            if (!$this->uid) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $r = Db::name('user_address')->where('del_time',null)->where(['user_id' => $this->uid])->field('del_time',true)->order('is_default desc,id desc')->select();
            if ($r) {
                return $this->splash(1, '获取成功', $r);
            } else {
                return $this->splash(0, '获取失败或没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /**
     * 用户地址，详情
     * contacts
     * mobile
     * province
     * city
     * area
     * address
     * is_default
     */
    public function address_info()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !$data['id']) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $r = Db::name('user_address')->where('del_time',null)->where(['id' => $data['id'], 'user_id' => $this->uid])->field('del_time',true)->find();
            if ($r) {
                return $this->splash(1, '获取成功', $r);
            } else {
                return $this->splash(0, '获取失败，请稍候重试');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /**
     * 用户地址，默认
     * contacts
     * mobile
     * province
     * city
     * area
     * address
     * is_default
     */
    public function address_default()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $r = Db::name('user_address')->where('del_time',null)->where([ 'user_id' => $this->uid])->field('del_time',true)->order('is_default desc,id asc')->find();
            if ($r) {
                return $this->splash(1, '获取成功', $r);
            } else {
                return $this->splash(0, '获取失败，请稍候重试');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /**
     * 用户地址，添加
     * contacts
     * mobile
     * province
     * city
     * area
     * address
     * is_default
     */
    public function address_save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (!isset($this->uid) || !isset($data['contacts']) || !isset($data['mobile']) || !isset($data['province']) || !isset($data['city']) || !isset($data['area']) || !isset($data['address']) || !isset($data['is_default'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $save = [
                'user_id' => $this->uid,
                'contacts' => $data['contacts'],
                'mobile' => $data['mobile'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'address' => $data['address'],
                'is_default' => $data['is_default'],
            ];
            if ($data['is_default'] == 1) {
                $r = Db::name('user_address')->where('del_time', null)->where(['user_id' => $this->uid, 'is_default' => 1])->find();
                if ($r) {
                    $d = Db::name('user_address')->where('del_time', null)->where(['user_id' => $this->uid])->update(['is_default' => 0]);
                    if (!$d) {
                        return $this->splash(0, '数据保存出现问题，请重试');
                    }
                }
            }
            if (isset($data['id']) && !empty($data['id'])) {
                //修改
                $r = Db::name('user_address')->where(['id' => $data['id']])->update($save);
            } else {
                //添加
                $save['add_time'] = time();
                $r = Db::name('user_address')->insertGetId($save);
            }
            if ($r) {
                return $this->splash(1, '保存成功');
            } else {
                return $this->splash(0, '保存失败，请稍候重试');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /**
     * 用户地址，删除
     * contacts
     * mobile
     * province
     * city
     * area
     * address
     * is_default
     */
    public function address_del()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !$data['id']) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $r = Db::name('user_address')->where('del_time', null)->where(['id' => $data['id'], 'user_id' => $this->uid])->update(['del_time' => time()]);
            if ($r) {
                return $this->splash(1, '获取成功');
            } else {
                return $this->splash(0, '获取失败，请稍候重试');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 设置安全密码
     *
     * */
    public function safe_password_save()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['safe_password'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $r = Db::name('user')->where(['id' => $this->uid])->update(['safe_password' => md5($data['safe_password'])]);
            if ($r) {
                return $this->splash(1, '更新成功');
            } else {
                return $this->splash(0, '更新失败');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 验证安全密码
     * */
    public function safe_password_check()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['safe_password'])) {
                return $this->splash(0, '信息不完整，请重试');
            }

            $r = Db::name('user')->where(['id' => $this->uid])->value('safe_password');
            if ($r) {
                if ($r == md5($data['safe_password'])){
                    $send = 1;
                    $msg = '密码正确';
                }else{
                    $send = 0;
                    $msg = '密码错误';
                }
                return $this->splash(1, $msg,$send);
            } else {
                return $this->splash(0, '查找失败');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /**
     * 上传图片 64
     */
    public function updateImage()
    {
        if ($this->request->isPost()) {
            $data=$this->request->param();
            if (empty($data['image'])) {
                return $this->splash(0, '请选择上传文件');
            }
            $image=$data['image'];
            $imageName = "rm_".date("His",time())."_".rand(1111,9999).'.png';
            if (strstr($image,",")){
                $image = explode(',',$image);
                $image = $image[1];
            }
            $path = 'public/uploads/user/'.date("Ymd",time());
            if (!is_dir($path)){ //判断目录是否存在 不存在就创建
                mkdir($path,0777,true);
            }
            $imageSrc= $path."/". $imageName; //图片名字
            $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
            if (!$r) {
                return json(['Status' => 0, 'Message' => '图片生成失败']);
            }else{
                return json(['Status' => 1, 'Message' => '图片生成成功', 'Data' => ['image'=>str_replace('public/','',$imageSrc),'url'=>'http://'.$_SERVER['SERVER_NAME'].'/public/']]);
            }
        }
    }
    /*
     * 修改个人信息
     * 头像 昵称 性别 年龄 手机号 注册时间
     * */
    public function user_load()
    {
        if($this->request->isPost()) {
            $r = Db::name('user')->where(['id' => $this->uid])->field('image,username,sex,wx,wx_code,level,in_user_id,contact,phone,province,province_id,city,city_id,area,area_id,address')->find();
            if ($r) {
                $r['img_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/public/';
                $r['up_user_mobile'] = Db::name('user')->where('id',$r['in_user_id'])->value('mobile');
//                $r['image'] = $r['image']?'http://'.$_SERVER['SERVER_NAME'].'/public/'.$r['image']:'';
//                $r['wx_code'] = $r['wx_code']?'http://'.$_SERVER['SERVER_NAME'].'/public/'.$r['wx_code']:'';
                return $this->splash(1, '获取成功',$r);
            } else {
                return $this->splash(0, '没有数据或获取失败');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 修改个人信息
     * 头像 姓名 性别 微信号 微信二维码
     * */
    public function user_save()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['image']) || !isset($data['username']) || !isset($data['sex']) || !isset($data['wx']) || !isset($data['wx_code']) || !isset($data['contact']) || !isset($data['phone']) || !isset($data['province']) || !isset($data['city']) || !isset($data['area']) || !isset($data['address']) || !isset($data['province_id']) || !isset($data['city_id']) || !isset($data['area_id'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $save = [
                'image'=>$data['image'],
                'username'=>$data['username'],
                'sex'=>$data['sex'],
                'wx'=>$data['wx'],
                'wx_code'=>$data['wx_code'],
                'contact' => $data['contact'],
                'phone' => $data['phone'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
                'area_id' => $data['area_id'],
                'address' => $data['address'],
            ];
            $r = Db::name('user')->where(['id' => $this->uid])->update($save);
            if ($r) {
                return $this->splash(1, '修改成功');
            } else {
                return $this->splash(0, '修改失败');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 修改个人信息
     * 单个改
     *
     * 头像 1
     * 昵称 2
     * 性别 3
     * 年龄 4
     * */
//    public function user_save()
//    {
//        if($this->request->isPost()) {
//            $data = $this->request->param();
//            if (!$this->uid || !isset($data['type']) || !isset($data['data'])) {
//                return $this->splash(0, '信息不完整，请重试');
//            }
//            $save = [];
//            switch ($data['type']) {
//                case 1:
//                    $save['image'] = $data['data'];
//                    break;
//                case 2:
//                    $save['username'] = $data['data'];
//                    break;
//                case 3:
//                    $save['sex'] = $data['data'];
//                    break;
//                case 4:
//                    $save['age'] = $data['data'];
//                    break;
//            }
//            $r = Db::name('user')->where(['id' => $this->uid])->update($save);
//            if ($r) {
//                return $this->splash(1, '修改成功');
//            } else {
//                return $this->splash(0, '修改失败');
//            }
//        }else{
//            return $this->splash(0, '请求错误');
//        }
//    }
    /*
     * 修改登录密码
     *
     * */
    public function password_save()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['password']) || !isset($data['old_password'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $user = Db::name('user')->where('id',$this->uid)->find();
            if($user['password']!=md5($data['old_password'])){
                return $this->splash(0, '原密码不正确');
            }
            $r = Db::name('user')->where(['id' => $this->uid])->update(['password' => md5($data['password'])]);
            if ($r) {
                return $this->splash(1, '更新成功');
            } else {
                return $this->splash(0, '更新失败');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
//    /**
//     * 通用图片上传接口
//     * @return \think\response\Json
//     */
//    public function upload_image()
//    {
//        $config = [
//            'size' => 2097152,
//            'ext'  => 'jpg,gif,png,bmp'
//        ];
//
//        $file = $this->request->file('image');
//        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads/user');
//        $save_path   = '/uploads/user/';
//        $info        = $file->validate($config)->move($upload_path);
//
//        if ($info) {
//            $result = [
//                'error' => 0,
//                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
//            ];
//        } else {
//            $result = [
//                'error'   => 1,
//                'message' => $file->getError()
//            ];
//        }
//
//        return json($result);
//    }
//    /*
//     * 关于我们
//     * */
//    public function aboutus()
//    {
//        $aboutus = unserialize(Db::table('os_system')->where(['name'=>'aboutus'])->value('value'));
//
//        $send = htmlspecialchars_decode($aboutus['content']);
//        $send = str_replace('src="','src="http://'.$_SERVER['SERVER_NAME'].'/',$send);
//        return $this->splash(1,'获取成功',$send);
//    }
}
